package com.heima.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {


    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //查询手机号是否存在
        ApUser apUser = this.lambdaQuery()
                .eq(ApUser::getPhone, dto.getPhone())
                .one();
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //判断密码是否正确
        //比较登录明文密码与表中密文密码是否匹配
        boolean checkpw = BCrypt.checkpw(dto.getPassword(), apUser.getPassword());
        if(!checkpw){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //判断账号状态
        if(apUser.getStatus()){
            return ResponseResult.errorResult(AppHttpCodeEnum.INVALID_STATUS);
        }
        Long id = Long.valueOf(String.valueOf(apUser.getId()));
        String token = AppJwtUtil.getToken(id);
        Map<String, Object> map = new HashMap<>();
        map.put("user",apUser);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
